// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#pragma once

#include <pollux/expression/complex_view_types.h>
#include <pollux/functions/udf.h>
#include <pollux/functions/prestosql/map_top_n_impl.h>

namespace kumo::pollux::functions {
    template<typename TExec>
    struct CompareKeys {
        POLLUX_DEFINE_FUNCTION_TYPES(TExec);

        using It = typename arg_type<Map<Orderable<T1>, Generic<T2> > >::Iterator;

        bool operator()(const It &l, const It &r) const {
            static const CompareFlags flags{
                false /*nullsFirst*/,
                true /*ascending*/,
                false /*equalsOnly*/,
                CompareFlags::NullHandlingMode::kNullAsIndeterminate
            };
            return l->first.compare(r->first, flags) > 0;
        }
    };

    // Returns an array with the top N keys in descending order.
    template<typename TExec>
    struct MapTopNKeysFunction : MapTopNImpl<TExec, CompareKeys<TExec> > {
    };
} // namespace kumo::pollux::functions
